package com.framework.admin.service.impl;

import com.framework.admin.domain.param.SysCompanyFormParam;
import com.framework.admin.domain.param.SysCompanyParam;
import com.framework.admin.domain.vo.SysCompanyVo;
import com.framework.admin.mapper.SysCompanyMapper;
import com.framework.admin.model.SysCompany;
import com.framework.admin.repository.SysCompanyRepository;
import com.framework.admin.service.ISysCompanyService;
import com.framework.common.util.BeanUtils;
import com.framework.file.api.FileService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 公司表
 * 2021-03-05 10:59:15
 */
@Service
public class SysCompanyService implements ISysCompanyService {
    @Autowired
    private SysCompanyMapper baseMapper;
    @Autowired
    private SysCompanyRepository baseRepo;
    @Autowired
    private FileService fileService;

    @Override
    public Page<SysCompanyVo> listPage(SysCompanyParam param, PageRequest pageRequest) {
        Page<SysCompanyVo> page = baseMapper.listPage(param, pageRequest);
        setLogoShowUrl(page.getContent());
        return page;
    }

    @Override
    public String save(SysCompanyFormParam param) {
        SysCompany entity = new SysCompany();
        BeanUtils.copyProperties(param, entity);
        baseRepo.save(entity);

        return entity.getId();
    }

    @Override
    public void delete(List<String> ids) {
        String[] arr = new String[ids.size()];
        baseRepo.deleteById(ids.toArray(arr));
    }

    @Override
    public void update(SysCompanyFormParam param) {
        baseRepo.updateById(param);
    }

	/**
	 * 设置logo预览地址
	 * @param list 列表
	 */
	private void setLogoShowUrl(List<SysCompanyVo> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        List<String> logoFileIdList = list.stream()
                .map(SysCompany::getLogo)
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toList());

        //logo url map
        Map<String, String> logoUrlMap = null;
        if (CollectionUtils.isNotEmpty(logoFileIdList)) {
            logoUrlMap = fileService.previewBatch(logoFileIdList).unwrap();
        }

        if (null != logoUrlMap) {
            for (SysCompanyVo sysCompanyVo : list) {
                sysCompanyVo.setLogoUrl(logoUrlMap.get(sysCompanyVo.getLogo()));
            }
        }
    }

    @Override
    public SysCompany findById(String id) {
        return baseRepo.findOne(id);
    }

    @Override
    public SysCompany findByUserId(String id) {
        return baseMapper.findByUserId(id);
    }
}
